package com.lemon.system.service.impl;

import com.lemon.core.web.Result;
import com.lemon.mybatisplus.base.BaseServiceImpl;
import com.lemon.mybatisplus.enums.DeleteEnum;
import com.lemon.mybatisplus.enums.StatusEnum;
import com.lemon.security.dto.LoginUserDetail;
import com.lemon.security.utils.JwtUtil;
import com.lemon.system.dao.MenuDAO;
import com.lemon.system.dto.MenuDTO;
import com.lemon.system.po.MenuPO;
import com.lemon.system.service.IMenuService;
import com.lemon.system.vo.RouteVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 菜单表 业务实现类
 *
 * @author 李猛
 * @since 2024-02-11
 */
@Log4j2
@Service
public class MenuServiceImpl extends BaseServiceImpl<MenuDAO, MenuPO, MenuDTO> implements IMenuService {
    @Override
    public Result<List<RouteVO>> getRoutes() {
        //1.当前用户信息
        LoginUserDetail currentUser = JwtUtil.getCurrentUser();

        //2.查询web_file_path
        Map<String, Object> param = new HashMap<>();
        param.put("userId", currentUser.getUserId());
        param.put("tenantId", currentUser.getTenantId());
        param.put(StatusEnum.ENABLE.getColumn(), StatusEnum.ENABLE.getValue());
        param.put(DeleteEnum.UNABLE.getColumn(), DeleteEnum.UNABLE.getValue());
        List<String> webFilePathList = this.baseMapper.getWebFilePathByUserId(param);
        if (CollectionUtils.isEmpty(webFilePathList)) {
            return Result.ok();
        }
        return Result.ok(webFilePathList.stream().map(toRoute).collect(Collectors.toList()));
    }

    /**
     * 获取RouteVO对象
     */
    private final Function<String, RouteVO> toRoute = (webPath -> {
        RouteVO route = new RouteVO();
        route.setComponent(webPath.endsWith(".vue") ? webPath : webPath + ".vue");
        route.setParentPath(webPath.substring(0, webPath.lastIndexOf("/")));
        route.setPath(webPath.substring(webPath.lastIndexOf("/") + 1, webPath.length() - 4).toLowerCase());
        return route;
    });
}